/* eslint-disable no-unneeded-ternary */
import React from 'react';
import {Spin, Card, Button, Row, Col, Table, Form, Popconfirm, message as msg, Switch} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, TABLE, FIXED_COLUMN_WIDTH} from '../constants';
import {getPartsDetail, updateData} from './api';
import {injectIntl, language} from './intl';
import TextInput from 'Shared/components/TextInput';
import WrappedSelect from '../common/WrappedSelect';
import {uuid} from '../utils';
import styles from './style.css';
import Return from '../common/Return';
import {isYesNo, partChannel} from '../Enum';
const FormItem = Form.Item;

class UpdatePanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        data: {},
        details: [],
    }
    componentDidMount() {
        const id = this.props.id;
        this.setState({loading: true});
        getPartsDetail(id)
            .then(res => {
                if(res.ok) {
                    if(typeof res.data.chemicalCheck === 'boolean')
                        res.data.chemicalCheck = (res.data.chemicalCheck === true ? 1 : 0);
                    if(typeof res.data.airMagneticCheck === 'boolean')
                        res.data.airMagneticCheck = (res.data.airMagneticCheck === true ? 1 : 0);
                    if(typeof res.data.businessCheck === 'boolean')
                        res.data.businessCheck = (res.data.businessCheck === true ? 1 : 0);
                    if(typeof res.data.dangerousGoods === 'boolean')
                        res.data.dangerousGoods = (res.data.dangerousGoods === true ? 1 : 0);
                    if(typeof res.data.remoteControl === 'boolean')
                        res.data.remoteControl = (res.data.remoteControl === true ? 1 : 0);
                    if(typeof res.data.cvJointKit === 'boolean')
                        res.data.cvJointKit = (res.data.cvJointKit === true ? 1 : 0);
                    this.setState({
                        loading: false,
                        data: res.data,
                        details: res.data.partSalesProperty,
                    });
                } else
                    this.setState({loading: false});
            });
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const data = this.state.data;
        const details = this.state.details;
        const condition = {
            chemicalCheck: data.chemicalCheck === 1 ? true : false,
            airMagneticCheck: data.airMagneticCheck === 1 ? true : false,
            businessCheck: data.businessCheck === 1 ? true : false,
            dangerousGoods: data.dangerousGoods === 1 ? true : false,
            remoteControl: data.remoteControl === 1 ? true : false,
            cvJointKit: data.cvJointKit === 1 ? true : false,
            rowVersion: data.rowVersion,
            channel: data.channel,
            details: details.map(v => ({
                brandId: v.brandId,
                saleable: v.saleable,
                remark: v.remark,
            }))
        };
        this.setState({loading: true});
        updateData(this.props.id, condition).then(res => {
            if(res.ok)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }

    onDeleteAll = () => {
        this.setState({
            details: [],
            hasOperat: true
        });
    }
    onDeleteDetail = e => {
        const id = e.target.dataset.id;
        const details = this.state.details.filter(p => p.id !== id);
        this.setState({
            details,
            hasOperat: true
        });
    }
    onClickAddDetailBtn = () => {
        const details = this.state.details;
        this.setState({
            details: [
                ...details,
                {
                    id: uuid()
                }
            ]
        });
    };
    onChangeAll = (value, id, e) => {
        const details = this.state.details || [];
        const name = e.target.name;
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    [name]: value
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    onSwitchChange = (value, name, id) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    [name]: value,
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    onBrandChange = (brandId, id) => {
        const details = this.state.details || [];
        const index = details.findIndex(v => v.brandId === brandId);
        if(index === 0)
            return msg.warn(this.props.intl.formatMessage({
                id: 'updatePanel.message.brand',
                defaultMessage: '已存在该品牌'
            }));
        const tmp = details.map(d => {
            const index = details.findIndex(v => v.brandId === brandId);
            if(d.id === id && index === -1)
                return Object.assign({}, d, {
                    brandId,
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, isValidate, loading} = this.state;
        const {brands} = this.props.initEnumData;
        const columns = [
            {
                title: formatMessage({
                    id: 'updatePanel.column.brand',
                    defaultMessage: '品牌'
                }),
                width: 150,
                dataIndex: 'brandId',
                render: (text, record) => {
                    const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate}>
                            <WrappedSelect
                                id={record.id}
                                options={brands}
                                value={record.brandId}
                                onChange={this.onBrandChange} />
                        </FormItem>
                    );
                }
            }, {
                title: formatMessage({
                    id: 'updatePanel.column.saleable',
                    defaultMessage: '是否可销售'
                }),
                dataIndex: 'saleable',
                render: (text, record) => (
                    <FormItem>
                        <Switch
                            checkedChildren={formatMessage({
                                id: 'yes',
                                defaultMessage: '是'
                            })}
                            unCheckedChildren={formatMessage({
                                id: 'no',
                                defaultMessage: '否'
                            })}
                            checked={text}
                            value={record.saleable}
                            id={record.id}
                            onChange={value => this.onSwitchChange(value, 'saleable', record.id)} />
                    </FormItem>
                )
            }, {
                title: formatMessage({
                    id: 'updatePanel.column.remark',
                    defaultMessage: '备注'
                }),
                dataIndex: 'remark',
                render: (text, record) => (
                    <FormItem>
                        <TextInput
                            id={record.id}
                            name="remark"
                            value={text} onBlur={this.onChangeAll}/>
                    </FormItem>
                )
            }, {
                title: details.length > 0
                    ? (
                        <Popconfirm placement="topRight" title={formatMessage({
                            id: 'updatePanel.validation.isDelete',
                            defaultMessage: '是否确认全部删除？'
                        })} onConfirm={this.onDeleteAll} >
                            <a>{formatMessage({
                                id: 'updatePanel.validation.clear',
                                defaultMessage: '清空'
                            })}</a>
                        </Popconfirm>
                    )
                    : null,
                dataIndex: 'id',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: text => <a data-id={text} onClick={this.onDeleteDetail}>{formatMessage({
                    id: 'updatePanel.validation.delete',
                    defaultMessage: '删除'
                })}</a>
            }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'updatePanel.column.common',
                        defaultMessage: '备件检查属性'
                    })}>
                        <Form>
                            <Row>
                                <Row>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={formatMessage({
                                                id: 'updatePanel.form.code',
                                                defaultMessage: '备件编号'
                                            })}{...FORM_OPTIONS.item}>
                                            {data.code}
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={formatMessage({
                                                id: 'updatePanel.form.name',
                                                defaultMessage: '备件名称'
                                            })}{...FORM_OPTIONS.item}>
                                            {data.name}
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'updatePanel.form.chemicalCheck',
                                            defaultMessage: '化工鉴定'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                            <WrappedSelect
                                                allowClear
                                                name="chemicalCheck"
                                                value={data.chemicalCheck}
                                                options={isYesNo.toList(language)}
                                                onChange={this.onChange} />
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'updatePanel.form.airMagneticCheck',
                                            defaultMessage: '空运磁检'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                            <WrappedSelect
                                                allowClear
                                                name="airMagneticCheck"
                                                value={data.airMagneticCheck}
                                                options={isYesNo.toList(language)}
                                                onChange={this.onChange} />
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'updatePanel.form.businessCheck',
                                            defaultMessage: '商检'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                            <WrappedSelect
                                                allowClear
                                                name="businessCheck"
                                                value={data.businessCheck}
                                                options={isYesNo.toList(language)}
                                                onChange={this.onChange} />
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'updatePanel.form.dangerousGoods',
                                            defaultMessage: '空运危险'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                            <WrappedSelect
                                                allowClear
                                                name="dangerousGoods"
                                                value={data.dangerousGoods}
                                                options={isYesNo.toList(language)}
                                                onChange={this.onChange} />
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'updatePanel.form.remoteControl',
                                            defaultMessage: '遥控器'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                            <WrappedSelect
                                                allowClear
                                                name="remoteControl"
                                                value={data.remoteControl}
                                                options={isYesNo.toList(language)}
                                                onChange={this.onChange} />
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'updatePanel.form.cvJointKit',
                                            defaultMessage: '球笼修理包'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                            <WrappedSelect
                                                allowClear
                                                name="cvJointKit"
                                                value={data.cvJointKit}
                                                options={isYesNo.toList(language)}
                                                onChange={this.onChange} />
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'updatePanel.form.channel',
                                            defaultMessage: '渠道'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                            <WrappedSelect
                                                allowClear
                                                name="channel"
                                                value={data.channel}
                                                options={partChannel.toList(language)}
                                                onChange={this.onChange} />
                                        </FormItem>
                                    </Col>
                                </Row>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'updatePanel.operation.detail',
                            defaultMessage: '备件销售属性'
                        })}>
                        <Button
                            type="dashed"
                            icon="plus"
                            block
                            disabled={this.state.details.length >= 1}
                            className={styles.plusBtn}
                            onClick={this.onClickAddDetailBtn}>
                            {formatMessage({
                                id: 'updatePanel.couponInfo.operation.new',
                                defaultMessage: '新增'
                            })}
                        </Button>
                        <Table
                            className="white-space-nowrap"
                            columns={columns}
                            rowKey="id"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            loading={loading}>
                            {formatMessage({
                                id: 'updatePanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

UpdatePanel.propTypes = {
    initEnumData: PropTypes.object.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    searchList
} from './actions';
import {createSelector} from 'reselect';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: item.name,
            value: item.id
        })) : [];
        return {
            brands
        };
    }
);
const mapStateToProps = state => ({
    initEnumData: getinitEnumData(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(searchList());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(UpdatePanel));
